package com.cictec.middleware.gps.engine.position.handler;

import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.cictec.middleware.commons.utils.Constants;
import com.cictec.middleware.commons.utils.DateUtils;
import com.cictec.middleware.commons.utils.gps.GpsUtils;
import com.cictec.middleware.gps.engine.BusInstance;
import com.cictec.middleware.gps.engine.TimingPoint;
import com.cictec.middleware.gps.engine.exception.BusPositionHandlerException;
import com.cictec.middleware.gps.engine.position.BusPositionHandler;

/**
 * 位置信息漂移判定
 * @author ql
 * @date 2017年8月31日
 */
@Component
public class BusPositionDriftHandler implements BusPositionHandler {

	private static Logger logger = LoggerFactory.getLogger(BusPositionDriftHandler.class);
	
	@Override
	public void onHandler(BusInstance busInstance) throws BusPositionHandlerException {

		
		List<TimingPoint> points = busInstance.getTimingSequential();
		boolean isDrift = false;
		if (points.size() >= 2) {
			TimingPoint prePoint = busInstance.getTimingPoint(-1);
			TimingPoint currentPoint = busInstance.getTimingPoint(0);

			isDrift = isDrift(prePoint.getTime(), prePoint.getLatitude(), prePoint.getLongitude(),
					currentPoint.getTime(), currentPoint.getLatitude(), currentPoint.getLongitude(),
					currentPoint.getSpeed());

			busInstance.setAttributeDrift(isDrift ? Constants.MSG_INFO_GPS_DRIFT_0 : Constants.MSG_INFO_GPS_DRIFT_1);

			if (isDrift) {
				// 移除漂移点
				busInstance.removeLastTimingPoint();
			}
		}
		
		
		logger.debug("【漂移判定】：{}",(isDrift == true? "漂移":"不漂移"));
	}

	/**
	 * 两点判断漂移
	 * 
	 * @param preBp
	 * @param currentBp
	 * @return
	 */
	private boolean isDrift(Date pred, String prelat, String prelng, Date currentd, String currentlat, String currentlng, String currentSpeed) {
		double millsPerSec = Constants.VAL_MAX_SPEED * 1000 / 3600;

		double leng = GpsUtils.getDistance(prelat, prelng, currentlat, currentlng);
		double interval = millsPerSec * DateUtils.secondInterval(pred, currentd);

		if (leng <= interval && Double.parseDouble(currentSpeed) < Constants.VAL_MAX_SPEED) {
			return false;
		}

		return true;
	}

}
